<template>
  <div class="ai-question-container">

    <el-card class="question-card" :body-style="{ padding: '20px' }">
      <div class="question-header">
        <h2 class="question-title">AI 出题</h2>
       <!-- <p style="margin-left: 700px" class="question-subtitle">选择科目和难度，生成个性化题目</p>-->
      </div>

      <el-form ref="questionForm" :model="questionForm" label-width="120px" class="question-form">
        <div class="select-area">
        <el-form-item label="选择科目">
          <el-select
            v-model="subject"
            placeholder="请选择科目"
            class="select-field"
            style="width: 100%; min-width: 300px;"
            clearable
            @change="onSubjectChange"
          >
            <el-option label="数据结构" value="数据结构"></el-option>
            <el-option label="计算机组成原理" value="计算机组成原理"></el-option>
            <el-option label="操作系统" value="操作系统"></el-option>
            <el-option label="计算机网络" value="计算机网络"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择难度">
          <el-select
            v-model="difficulty"
            placeholder="请选择难度"
            class="select-field"
            style="width: 100%; min-width: 300px;"
            clearable
            @change="onDifficultyChange"
          >
            <el-option label="⭐️" value="1"></el-option>
            <el-option label="⭐️⭐️" value="2"></el-option>
            <el-option label="⭐️⭐️⭐️" value="3"></el-option>
            <el-option label="⭐️⭐️⭐️⭐️" value="4"></el-option>
            <el-option label="⭐️⭐️⭐️⭐️⭐️" value="5"></el-option>
          </el-select>
        </el-form-item>
        </div>
        <el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            @click="generateQuestion"
            class="generate-button"
            style="margin-left: -100px;margin-top:-5px;margin-bottom:-15px;width: 125px"
          >
            <el-icon class="button-icon"><MagicStick /></el-icon>
            生成题目
          </el-button>
        </el-form-item>
      </el-form>

      <div v-if="error" class="error-message">
        <el-alert :title="error" type="error" show-icon :closable="false"></el-alert>
      </div>
    </el-card>

    <transition name="fade">
      <el-card class="question-display" v-if="question">
        <div class="question-content">
          <div class="question-content-title">
            <h3 class="question-subject">{{ question.subject }}</h3>
            <h2 class="question-difficulty">难度：{{ question.difficulty }}</h2>
          </div>

          <p class="question-description">{{ question.description }}</p>
          <div v-if="!showAnswer" class="question-options">
            <el-radio-group v-model="userAnswer">
              <el-radio-button
                v-for="(option, index) in question.options"
                :key="index"
                :label="option"
              >
                {{ option }}
              </el-radio-button>
            </el-radio-group>
            <el-button type="success" @click="showAnswer = true">提交答案</el-button>
          <!-- <el-button type="warning" @click="addToFavorites">收藏</el-button>--> 
          </div>
          <div v-else class="question-answer">
            <p>你的答案：{{ userAnswer }}</p>
            <p>正确答案：{{ question.answer }}</p>
            <p>解析：{{ question.explanation }}</p>
          </div>
        </div>
      </el-card>
    </transition>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import axios from 'axios';
import { MagicStick } from '@element-plus/icons-vue';

export default {
  name: 'AIQuestion',
  components: {
    MagicStick,
  },
  setup() {
    const subject=ref('')
    const difficulty=ref('')
    const questionForm = ref({
      subject: '',
      difficulty: '',
    });
    const question = ref(null);
    const error = ref(null);
    const loading = ref(false);
    const userAnswer = ref('');
    const showAnswer = ref(false);

    const onSubjectChange = (value) => {
      questionForm.value.subject = value;
      console.log('Selected subject:', value);
      console.log('Current questionForm:', questionForm.value);
    };

    const onDifficultyChange = (value) => {
      questionForm.value.difficulty=value;
      console.log('Selected difficulty:', value);
      console.log('Current questionForm:', questionForm.value);
    };

    const generateQuestion = async () => {
      if (!questionForm.value.subject || !questionForm.value.difficulty) {
        ElMessage.error('请选择科目和难度');
        return;
      }

      loading.value = true;
      try {
        const token = localStorage.getItem('token');
        console.log('JWT Token:', token);
        if (!token) {
          throw new Error('未找到有效的 JWT Token，请先登录');
        }

        const inputString = `科目: ${questionForm.value.subject}, 难度: ${questionForm.value.difficulty}`;
        console.log('Request input:', inputString);

        // 确保 difficulty 是一个整数
        const difficulty = parseInt(questionForm.value.difficulty, 10);

        const response = await axios.post('http://localhost:8080/aichat/question', {
          subject: questionForm.value.subject,
          difficulty: difficulty,
        }, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
          },
        });

        console.log('Response data:', response.data);

        if (response.data && response.data.code === 0) {
          try {
            // 解析 data 字段为 JSON 对象
            const questionData = JSON.parse(response.data.data);
            question.value = {
              subject: questionForm.value.subject,
              difficulty: '⭐️'.repeat(difficulty),
              description: questionData.question,
              options: questionData.options, // 添加选项
              answer: questionData.answer,
              explanation: questionData.explanation, // 添加解析
            };
            userAnswer.value = ''; // 清空用户答案
            showAnswer.value = false; // 隐藏答案
            error.value = null;
          } catch (parseError) {
            console.error('Error parsing question data:', parseError);
            error.value = '生成题目失败，请稍后再试';
          }
        } else if (response.data && response.data.message) {
          error.value = response.data.message;
        } else {
          error.value = '生成题目失败，请稍后再试';
        }
      } catch (error) {
        console.error('Error generating question:', error);
        if (error.response) {
          error.value = error.response.data.error || `服务器错误: ${error.response.status} - ${JSON.stringify(error.response.data)}`;
        } else if (error.request) {
          error.value = '无法连接到服务器，请检查网络或服务器状态';
        } else {
          error.value = error.message || '生成题目失败，请稍后再试';
        }
      } finally {
        loading.value = false;
      }
    };

    const addToFavorites = async () => {
      if (!question.value) {
        ElMessage.error('没有题目可收藏');
        return;
      }

      const token = localStorage.getItem('token');
      if (!token) {
        ElMessage.error('请先登录');
        return;
      }

      try {
        const response = await axios.post('http://localhost:8080/favorite/add', {
          userId: 1, // 假设用户ID为1，实际应从用户信息中获取
          messageId: question.value.questionId, // 假设题目有 messageId 字段
          content: question.value.description,
          answer: question.value.answer,
          analysis: question.value.explanation,
          type: 1, // 假设类型为1表示选择题
        }, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`,
          },
        });

        if (response.data && response.data.code === 0) {
          ElMessage.success('收藏成功');
        } else {
          ElMessage.error(response.data.message || '收藏失败');
        }
      } catch (error) {
        console.error('Error adding to favorites:', error);
        ElMessage.error(error.response?.data?.msg || '无法连接到后端服务');
      }
    };

    return {
      subject,difficulty,
      questionForm,
      question,
      error,
      loading,
      userAnswer,
      showAnswer,
      generateQuestion,
      addToFavorites,
      onSubjectChange,
      onDifficultyChange,
    };
  },
};
</script>

<style scoped lang="scss">
.ai-question-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  min-height: 77vh;
  border-radius: 20px;
}

.question-card {
  width: 60vw;
  margin-bottom: 20px;
  background-color: $global-background-color;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

/*取消上移动画
.question-card:hover {
  transform: translateY(-5px);
}
*/

.question-header {
  text-align: center;
  margin-bottom: 20px;

}

.question-title {
  font-size: 24px;
  color: $global-font-color;
  margin: 0;
}

.question-subtitle {
  font-size: 14px;
  color: $global-font-color;
  margin: 5px 0 0;
}

.question-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.select-area{
  display: flex;
  justify-content: space-between;
}

.select-field {
  width: 100%;
  max-width: 400px;
  min-width: 300px;
}

.generate-button {
  width: 100%;
  max-width: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
  font-size: 16px;
  padding: 12px 20px;
  margin-top: 20px;
  transition: background-color 0.3s ease;
}

.generate-button:hover {
  background-color: #66b1ff;
}

.button-icon {
  margin-right: 8px;
}

.error-message {
  margin-top: 20px;
}

.question-display {
  width: 100%;
  max-width: 600px;
  margin-top: 20px;
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

/*
.question-display:hover {
  transform: translateY(-5px);
}
*/

.question-content {
  text-align: center;
}

.question-subject {
  font-size: 18px;
  color: #333333;
  margin: 0 0 10px;
}

.question-difficulty {
  font-size: 14px;
  color: #666666;
  margin: 0 0 10px;
}

.question-description {
  font-size: 16px;
  color: #333333;
  margin: 0 0 10px;
}

.question-options {
  font-size: 16px;
  color: #333333;
  margin: 0 0 10px;
}

.question-answer {
  font-size: 16px;
  color: #333333;
  margin: 0 0 10px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
.question-content-title{
  display: flex;
  justify-content: space-between
}
</style>